#include "process_pool.h"

int makeChild(process_data * pProcess, int num)
{
    for(int i = 0; i < num; ++i) {
        int fds[2];
        socketpair(AF_LOCAL, SOCK_STREAM, 0, fds);
        pid_t pid = fork();
        if(pid == 0) {//子进程
            close(fds[1]);
            //子进程执行任务
            doTask(fds[0]);
            exit(0);
        } 
        //父进程
        close(fds[0]);
        //记录子进程的信息
        pProcess[i].pid = pid;
        pProcess[i].pipefd = fds[1];//与子进程通信的管道
        pProcess[i].status = FREE;
    }
    return 0;
}

int doTask(int pipefd)
{
    printf("proces %d is doTask...\n", getpid());
    while(1)
    {
        int peerfd = -1;
        //子进程不断地读取管道中传递过来的peerfd
        recvFd(pipefd, &peerfd);
        //发送文件的操作
        transferFile(peerfd);
        printf("child %d send finish.\n", getpid());

        //关闭peerfd
        close(peerfd);

        //通知父进程，任务执行完毕
        int one = 1;
        write(pipefd, &one, sizeof(one));
    }

    return 0;
}
